package com.sunwayworld.basemodule.samplemanage.sample.io;

import com.sunwayworld.baseline.framework.override.LimsExcelHelper;
import com.sunwayworld.basemodule.basedata.sampletype.bean.LimsSampleTypeBean;
import com.sunwayworld.basemodule.basedata.sampletype.service.LimsSampleTypeService;
import com.sunwayworld.basemodule.business.ordertask.bean.LimsOrderTaskBean;
import com.sunwayworld.basemodule.business.ordertask.service.LimsOrderTaskService;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.i18n.I18nHelper;
import com.sunwayworld.framework.io.file.FilePathDTO;
import com.sunwayworld.framework.io.file.FilePathManager;
import com.sunwayworld.framework.mybatis.mapper.MapperParameter;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.ServletUtils;
import com.sunwayworld.framework.utils.StringUtils;
import com.sunwayworld.module.item.file.bean.CoreFileBean;
import com.sunwayworld.module.item.file.bean.CoreFileImportResultDTO;
import com.sunwayworld.module.item.file.function.CoreFileImportFunction;
import com.sunwayworld.module.item.file.manager.CoreFileManager;
import com.sunwayworld.module.item.file.utils.CoreFileUtils;
import com.sunwayworld.module.sys.code.bean.CoreCodeBean;
import com.sunwayworld.module.sys.code.service.CoreCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @ClassName LimsDeriSampleGenerateImportFileFunction
 * @Author zhoujq
 * @Date 2023/3/15
 * @Version 1.0
 **/
@Component(value = "LimsDeriSampleGenerateImportFileFunction")
@GikamBean
public class LimsDeriSampleGenerateImportFileFunction implements CoreFileImportFunction {

    @Autowired
    private LimsOrderTaskService limsOrderTaskService;

    @Autowired
    @Lazy
    private LimsSampleTypeService limsSampleTypeService;

    @Autowired
    @Lazy
    private CoreCodeService coreCodeService;

    @Override
    @Transactional
    public CoreFileImportResultDTO apply(CoreFileBean coreFileBean) {
        CoreFileImportResultDTO importResultRepresentation = new CoreFileImportResultDTO();
        FilePathDTO fr = CoreFileUtils.toFilePath(coreFileBean);

        // 从tos服务器下载
        CoreFileManager coreFileManager = ApplicationContextHelper.getBean(CoreFileManager.class);
        coreFileManager.download(coreFileBean, FilePathManager.getLocalPath(fr));

        List<LimsOrderTaskBean> orderTaskBeans = LimsExcelHelper.readDataFromExcel(FilePathManager.getLocalPath(fr).toString(), 1, 2, LimsOrderTaskBean.class);
        String runId = ServletUtils.getCurrentRequest().getParameter("runId");
        List<LimsOrderTaskBean> realTasks = limsOrderTaskService.selectListByFilter(SearchFilter.instance().match("runId", runId).filter(MatchPattern.EQ));
        orderTaskBeans.forEach(ot -> {
            if (StringUtils.isBlank(ot.getGenerateDerivativeType())) {
                if (!StringUtils.isBlank(ot.getExt$Item("validateimpmsg"))) {
                    ot.setExt$Item("validateimpmsg", ot.getExt$Item("validateimpmsg").concat("【生成方式】必须填写；"));
                } else {
                    ot.setExt$Item("validateimpmsg", "【生成方式】必须填写；");
                }
            }
            if (StringUtils.isBlank(ot.getDerivativeSampleType())) {
                if (!StringUtils.isBlank(ot.getExt$Item("validateimpmsg"))) {
                    ot.setExt$Item("validateimpmsg", ot.getExt$Item("validateimpmsg").concat("【衍生物类型】必须填写；"));
                } else {
                    ot.setExt$Item("validateimpmsg", "【衍生物类型】必须填写；");
                }
            }
            if (("mix".equalsIgnoreCase(ot.getGenerateDerivativeType()) || "混样".equalsIgnoreCase(ot.getGenerateDerivativeType())) && StringUtils.isBlank(ot.getMixGroupId())) {
                if (!StringUtils.isBlank(ot.getExt$Item("validateimpmsg"))) {
                    ot.setExt$Item("validateimpmsg", ot.getExt$Item("validateimpmsg").concat("混样样本的混样分组号必填；"));
                } else {
                    ot.setExt$Item("validateimpmsg", "混样样本的混样分组号必填；");
                }
            }
            if (realTasks.stream().noneMatch(rt -> rt.getId().equals(ot.getId()))) {
                if (!StringUtils.isBlank(ot.getExt$Item("validateimpmsg"))) {
                    ot.setExt$Item("validateimpmsg", ot.getExt$Item("validateimpmsg").concat("与当前批次不匹配；"));
                } else {
                    ot.setExt$Item("validateimpmsg", "与当前批次不匹配；");
                }
            }
        });

        // 返还校验结果
        if (orderTaskBeans.stream().anyMatch(i -> !StringUtils.isEmpty(i.getExt$Item("validateimpmsg")))) {
            FilePathDTO filePathDTO = LimsExcelHelper.writeImportFailureListAsExcel(FilePathManager.getLocalPath(fr).toString(), orderTaskBeans, 1, 2, "导入错误信息.xlsx", false);
            importResultRepresentation.setUrl(FilePathManager.getUrl(filePathDTO));
            importResultRepresentation.setMessage("导入失败");
            return importResultRepresentation;
        }

        MapperParameter mapperParameter = new MapperParameter();
        mapperParameter.put("filter_derivativeType", "1");
        List<LimsSampleTypeBean> sampleTypeBeans = limsSampleTypeService.selectList(mapperParameter);

        List<CoreCodeBean> deriTypes = coreCodeService.selectListByFilter(SearchFilter.instance().match("codeCategoryId", "derivativeMakeType").filter(MatchPattern.EQ));

        orderTaskBeans.forEach(ot -> {
            sampleTypeBeans.stream().filter(st -> st.getSampleTypeName().equalsIgnoreCase(ot.getDerivativeSampleType())).findAny().ifPresent(st -> {
                ot.setDerivativeSampleType(st.getSampleTypeCode());
                ot.setDerivativeSampleTypeCode(st.getSampleTypeCode());
            });
            deriTypes.stream().filter(dt -> dt.getCodeName().equalsIgnoreCase(ot.getGenerateDerivativeType())).findAny().ifPresent(dt -> {
                ot.setGenerateDerivativeType(dt.getCode());
            });
            if ("derivative".equalsIgnoreCase(ot.getGenerateDerivativeType())) {
                ot.setMixGroupId(null);
            }
        });

        limsOrderTaskService.getDao().update(orderTaskBeans, "mixGroupId", "derivativeSampleType", "generateDerivativeType", "derivativeSampleTypeCode");
        importResultRepresentation.setMessage("导入成功");
        return importResultRepresentation;

    }

    @Override
    public boolean test(CoreFileBean coreFile, String service) {
        return true;
    }
}
